package com.knowledge.plus.多线程.并发;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 单例情况下的高并发验证
 *
 * @author aFei
 * @since 2023/5/31
 */
@RestController
@RequestMapping
public class SingletonMultiThreadController {

    @Resource
    private SingletonBean singletonBean;

    /**
     * 先调用接口 http://localhost:40001/multiThread/1，模拟一次客户端请求
     * 而后立即调用接口 http://localhost:40001/multiThread/2
     * <p>
     * >>> 打印结果：
     * >>> request = n 请求时：里斯  28
     * >>> request = 1 请求时：里斯  28
     * 由结果可知：单例对象中的变量被修改了（request=1时对单例属性的赋值 在后面被修改了）
     */
    @GetMapping("multiThread/{request}")
    public void multiThreadValidate(@PathVariable("request") String request) throws InterruptedException {
        if (StringUtils.equals(request, "1")) {
            singletonBean.setName("张三");
            singletonBean.setAge(18);
            Thread.sleep(10000); // 睡眠10s，模拟业务逻辑执行时间
            System.out.println("request = 1 请求时：" + singletonBean.getName() + "  " + singletonBean.getAge());
        } else {
            singletonBean.setName("里斯");
            singletonBean.setAge(28);
            Thread.sleep(2000);
            System.out.println("request = n 请求时：" + singletonBean.getName() + "  " + singletonBean.getAge());
        }

    }

}
